package com.vcit.system.service.student.impl;

import java.util.List;

import com.vcit.common.core.domain.entity.SysDept;
import com.vcit.common.core.domain.entity.TStudent;
import com.vcit.common.exception.ServiceException;
import com.vcit.common.utils.DateUtils;
import com.vcit.common.utils.SecurityUtils;
import com.vcit.common.utils.StringUtils;
import com.vcit.system.domain.clazz.TClazz;
import com.vcit.system.domain.clazz.TClazzStudent;
import com.vcit.system.domain.major.TMajor;
import com.vcit.system.domain.student.StudentDTO;
import com.vcit.system.domain.vo.StudentListVo;
import com.vcit.system.mapper.SysDeptMapper;
import com.vcit.system.mapper.clazz.TClazzMapper;
import com.vcit.system.mapper.clazz.TClazzStudentMapper;
import com.vcit.system.mapper.major.TMajorMapper;
import com.vcit.system.mapper.student.TStudentMapper;
import com.vcit.system.service.student.ITStudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


/**
 * 学生Service业务层处理
 *
 * @author dff
 * @date 2025-01-17
 */
@Service
public class TStudentServiceImpl implements ITStudentService
{
    @Autowired
    private TStudentMapper tStudentMapper;

    @Autowired
    private TClazzStudentMapper tClazzStudentMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private TMajorMapper majorMapper;
    @Autowired
    private  TClazzMapper tClazzMapper;

    /**
     * 查询学生
     *
     * @param id 学生主键
     * @return 学生
     */
    @Override
    public StudentListVo selectTStudentById(Long id)
    {

        return tStudentMapper.selectTStudentVoById(id);
    }

    @Override
    public StudentListVo selectStudentVoById(Long id) {
        return tStudentMapper.selectTStudentVoById(id);
    }

    /**
     * 查询学生列表
     *
     * @param tStudent 学生
     * @return 学生
     */
    @Override
    public List<TStudent> selectTStudentList(TStudent tStudent)
    {
        return tStudentMapper.selectTStudentList(tStudent);
    }

    /**
     * 新增学生
     *
     * @param student 学生
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTStudent(StudentDTO student)
    {
       // System.out.println(student);
        student.setCreateBy(SecurityUtils.getUsername());
        student.setCreateTime(DateUtils.getNowDate());

        TStudent tStudent = new TStudent();
         BeanUtils.copyProperties(student, tStudent);
        tStudent.setZsStatus(8);
         tStudentMapper.insertTStudent(tStudent);// 学生信息新增

        TClazzStudent clazzStudent = new TClazzStudent();
        clazzStudent.setClazzId(student.getClazzId());
        clazzStudent.setCreateBy(SecurityUtils.getUsername());
        clazzStudent.setCreateTime(DateUtils.getNowDate());
        clazzStudent.setStudentId(tStudent.getId());


        return   tClazzStudentMapper.insertTClazzStudent(clazzStudent);// 学生--班级关联新增
    }

    /**
     * 修改学生
     *
     * @param student 学生
     * @return 结果
     */
    @Override
    public int updateTStudent(StudentDTO student)
    {



        student.setUpdateBy(SecurityUtils.getUsername());
        student.setUpdateTime(DateUtils.getNowDate());
        TStudent tStudent = new TStudent();
        BeanUtils.copyProperties(student, tStudent);
        tStudentMapper.updateTStudent(tStudent);

        TClazzStudent clazzStudent = new TClazzStudent();
        clazzStudent.setClazzId(student.getClazzId());
        clazzStudent.setUpdateBy(SecurityUtils.getUsername());
        clazzStudent.setUpdateTime(DateUtils.getNowDate());
        clazzStudent.setStudentId(student.getId());

        TClazzStudent studentIsEmpty = tClazzStudentMapper.selectTClazzStudentByStudentId(student.getId());
        if (studentIsEmpty != null){
            return tClazzStudentMapper.updateTClazzStudentByStudentId(clazzStudent);
        }else {
            return tClazzStudentMapper.insertTClazzStudent(clazzStudent);
        }

    }

    /**
     * 批量删除学生
     *
     * @param ids 需要删除的学生主键
     * @return 结果
     */
    @Override
    public int deleteTStudentByIds(Long[] ids)

    {
        tClazzStudentMapper.deleteTClazzStudentByStudentIds(ids);
        return tStudentMapper.deleteTStudentByIds(ids);
    }

    /**
     * 删除学生信息
     *
     * @param id 学生主键
     * @return 结果
     */
    @Override
    public int deleteTStudentById(Long id)

    {
        tClazzStudentMapper.deleteTClazzStudentByStudentId(id);
        return tStudentMapper.deleteTStudentById(id);
    }

    @Override
    public List<StudentListVo> selectStudentAllInfoList(StudentListVo studentListVo) {
        return tStudentMapper.selectStudentAllInfoVo(studentListVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importStudent(List<StudentListVo> studentList, Boolean updateSupport, String operName) {
        if (studentList == null || studentList.size() == 0) {
            throw new ServiceException("导入学生数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (StudentListVo student : studentList) {
            try {
                StudentDTO studentDTO = new StudentDTO();
                BeanUtils.copyProperties(student, studentDTO);
                // 部门名称找id
                SysDept dept = new SysDept();
                dept.setDeptName(student.getDeptName());
                List<SysDept> depts = sysDeptMapper.selectDeptList(dept);
                if (depts != null && depts.size() > 0) {
                    studentDTO.setDeptId(depts.get(0).getDeptId());
                }else {
                    throw  new ServiceException("导入失败，部门名称不存在");
                }
                // 专业名称 找专业id
                TMajor major = new TMajor();
                major.setMajorName(student.getMajorName());
                List<TMajor> majorList = majorMapper.selectTMajorList(major);
                if (majorList != null && majorList.size() > 0) {
                    studentDTO.setMajorId(majorList.get(0).getId());
                }else {
                    throw new ServiceException("导入失败，专业名称不对");
                }
                //根据班级名称找班级id
                TClazz clazz = new TClazz();
                clazz.setClazzName(student.getClazzName());
                List<TClazz> clazzes = tClazzMapper.selectTClazzList(clazz);

                if (clazzes != null && clazzes.size() > 0) {
                    studentDTO.setClazzId(clazzes.get(0).getId());
                }else {
                    throw new ServiceException("导入失败，班级名称不对");
                }
                studentDTO.setZsStatus(8);
                // 验证是否存在这个学生
                TStudent tStudent = tStudentMapper.selectTStudentBySno(student.getSno());
                if (tStudent == null) {
                    // 新增学生

                    studentDTO.setCreateBy(operName);
                    studentDTO.setCreateTime(DateUtils.getNowDate());
                    //
                    studentDTO.setZsStatus(8);
                    this.insertTStudent(studentDTO);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学号 " + student.getSno() + " 导入成功");
                } else if (updateSupport) {
                    // 更新学生信息

                    studentDTO.setId(tStudent.getId());
                    studentDTO.setUpdateBy(operName);
                    studentDTO.setUpdateTime(DateUtils.getNowDate());

                    //

                    studentDTO.setZsStatus(8);
                    this.updateTStudent(studentDTO);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学号 " + student.getSno() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学号 " + student.getSno() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学号 " + student.getSno() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
               // log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public TStudent selectStudentByName(String name) {
        return tStudentMapper.selectStudentByName(name);
    }

    @Override
    public TStudent selectStudentByIdCard(String idCard) {
        return tStudentMapper.selectStudentByIdCard(idCard);
    }

    @Override
    public boolean checkIdCardUnique(TStudent student) {
        Long studentId = StringUtils.isNull(student.getId()) ? -1L : student.getId();
        TStudent info = tStudentMapper.selectStudentByIdCard(student.getIdCard());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != studentId.longValue())
        {
            return false;
        }
        return true;
    }
}